/*******************************************************************************
 * Copyright (c) 2012 March and Conquest.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package mrusanov.towers.net;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import mrusanov.towers.configuration.GamefieldConfiguration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Communicator {

	private final static Logger LOG = LoggerFactory.getLogger(Communicator.class);

	private volatile boolean active;
	private Socket socket;
	private ServerSocket serverSocket;
	private ObjectInputStream input;
	private ObjectOutputStream output;
	private Boolean server;

	public void initServerSocket(int port) throws Exception {
		try {
			server = true;
			active = true;
			serverSocket = new ServerSocket(port);
			socket = serverSocket.accept();
			LOG.info("Accepted socket " + socket.toString());
			input = new ObjectInputStream(socket.getInputStream());
			LOG.info("Input stream initialized");
			output = new ObjectOutputStream(socket.getOutputStream());
			LOG.info("Output stream initialized");

		} catch (Exception ex) {
			handleExceptionInInitBlock(ex);
		}
	}

	private void handleExceptionInInitBlock(Exception ex) throws Exception {
		boolean activeBeforeDispose = active;
		dispose();
		if (activeBeforeDispose) {
			throw ex;
		}
	}

	public void sendStartingPlayer(StartingPlayer startingPlayer) throws Exception {
		try {
			output.writeObject(startingPlayer);
			output.flush();
		} catch (Exception ex) {
			dispose();
			throw ex;
		}
	}

	public StartingPlayer receiveStartingPlayer() throws Exception {
		try {
			return (StartingPlayer) input.readObject();
		} catch (Exception e) {
			dispose();
			throw e;
		}
	}

	public void sendGamefieldConfiguration(GamefieldConfiguration configuration) throws Exception {
		try {
			output.writeObject(configuration);
			output.flush();
		} catch (Exception ex) {
			dispose();
			throw ex;
		}
	}

	public GamefieldConfiguration receiveGamefieldConfiguration() throws Exception {
		try {
			return (GamefieldConfiguration) input.readObject();
		} catch (Exception e) {
			dispose();
			throw e;
		}
	}

	public void initClientSocket(String host, int port) throws Exception {
		try {
			server = false;
			active = true;
			socket = new Socket(host, port);
			LOG.info("Created socket: " + socket.toString());
			output = new ObjectOutputStream(socket.getOutputStream());
			LOG.info("Output stream initialized");
			input = new ObjectInputStream(socket.getInputStream());
			LOG.info("Input stream initialized");

		} catch (Exception ex) {
			handleExceptionInInitBlock(ex);
		}
	}

	public TurnInfo receiveTurnInfo() throws Exception {
		try {
			return (TurnInfo) input.readObject();
		} catch (Exception e) {
			dispose();
			throw e;
		}
	}

	public boolean isServer() {
		return server;
	}

	public boolean isActive() {
		return active;
	}

	public void sendTurnInfo(TurnInfo turnInfo) throws Exception {
		try {
			output.writeObject(turnInfo);
			output.flush();
		} catch (Exception ex) {
			dispose();
			throw ex;
		}
	}

	public String receivePlayerName() throws Exception {
		try {
			return (String) input.readObject();
		} catch (Exception ex) {
			dispose();
			throw ex;
		}
	}

	public void sendPlayerName(String name) throws Exception {
		try {
			output.writeObject(name);
			output.flush();
		} catch (Exception ex) {
			dispose();
			throw ex;
		}
	}

	public void dispose() {
		active = false;

		try {
			if (socket != null) {
				socket.close();
			}
		} catch (Exception ex) {
			LOG.error(ex.getMessage(), ex);
		}

		try {
			if (serverSocket != null) {
				serverSocket.close();
			}
		} catch (Exception ex) {
			LOG.error(ex.getMessage(), ex);
		}

	}
}
